package com.yt.user.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.vo.SysUserRoleVO;
import com.yt.user.models.bo.SysUserBO;
import com.yt.user.models.bo.SysUserSaveBO;
import com.yt.user.models.dto.SysUserDTO;
import com.yt.user.models.service.ISysUserService;
import com.yt.user.models.vo.SysUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息控制器
 *
 * @author zhao
 * @Date 2025-09-03 16:21:14
 */
@RestController
@RequestMapping("/api/sysUser")
@Slf4j
@Api(value = "SysUserApiController", tags = "用户信息Api接口")
public class SysUserApiController {

    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISysUserRoleService sysUserRoleService;

    @DubboReference
    private ISysRoleService sysRoleService;



    @ApiOperation(value = "新增用户", notes = "添加用户基本信息（账号、姓名等）")
    @PostMapping("/add")
    public Result<SysUserVO> add(@RequestBody SysUserSaveBO saveBO) {
        boolean success = sysUserService.add(saveBO);
        if (success) {
            // 通过唯一条件查询刚插入的记录（假设username唯一）
            SysUserDTO dto = sysUserService.selectOne(
                    new EntityWrapper<SysUserDTO>()
                            .eq("user_name", saveBO.getUserName())
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010); // 新增成功但查询失败
            }
            // 转换DTO到VO返回
            SysUserVO vo = new SysUserVO();
            BeanUtils.copyProperties(dto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100007); // 100007:新增失败
    }

    @ApiOperation(value = "更新用户", notes = "根据ID更新用户完整信息")
    @PutMapping("/update/{id}")
    public Result<SysUserVO> update(
            @PathVariable Long id,
            @RequestBody SysUserSaveBO saveBO) {

        // 校验记录是否存在
        SysUserDTO existingDto = sysUserService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在
        }

        // 复制更新字段并设置ID和更新时间
        SysUserDTO updateDto = new SysUserDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setUpdateTime(new Date());

        boolean success = sysUserService.updateById(updateDto);
        if (success) {
            // 查询更新后的最新记录
            SysUserDTO updatedDto = sysUserService.selectById(id);
            SysUserVO vo = new SysUserVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008); // 100008:更新失败
    }

    @ApiOperation(value = "更新用户状态", notes = "修改用户状态（0-禁用，1-正常）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态（0-禁用，1-正常）", required = true, paramType = "query", dataType = "Integer")
    })
    @PutMapping("/updateStatus/{id}")
    public Result updateStatus(
            @PathVariable Long id,
            Integer status) {

        // 校验记录是否存在
        SysUserDTO existingDto = sysUserService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在
        }

        SysUserDTO dto = new SysUserDTO();
        dto.setId(id);
        dto.setStatus(status);
        dto.setUpdateTime(new Date());
        boolean flag = sysUserService.updateById(dto);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "删除用户", notes = "物理删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "Long")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        // 先校验记录是否存在
        SysUserDTO dto = sysUserService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在
        }

        // 执行物理删除
        boolean success = sysUserService.deleteById(id);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }


    @ApiOperation(value = "查询用户详情", notes = "根据ID查询用户完整信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/get/{id}")
    public Result<SysUserVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysUserDTO dto = sysUserService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在
        }

        SysUserVO vo = new SysUserVO();
        BeanUtils.copyProperties(dto, vo);
        vo.setToken(null);
        return new Result<>(vo);
    }


    @ApiOperation(value = "分页查询用户列表", notes = "支持用户名和角色名模糊搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "roleName", value = "角色名（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "用户状态（0-禁用，1-正常）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageNo", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "startDate", value = "创建开始时间", paramType = "query", dataType = "Date"),
            @ApiImplicitParam(name = "endDate", value = "创建结束时间", paramType = "query", dataType = "Date")
    })
    @GetMapping("/list")
    public Result<Page<SysUserVO>> list(SysUserBO bo) {
        Page<SysUserVO> page = sysUserService.selectUserPage(bo);
        return new Result<>(page);
    }

    /**
     * 为用户VO设置角色信息
     */
    private void setUserRoles(SysUserVO userVO, Long userId) {
        try {
            // 查询用户关联的角色ID列表
            List<SysUserRoleVO> userRoles = sysUserRoleService.selectByUserId(userId);
            if (userRoles != null && !userRoles.isEmpty()) {
                List<Long> roleIds = userRoles.stream()
                        .map(SysUserRoleVO::getRoleId)
                        .collect(Collectors.toList());

                // 查询角色名称列表
                List<String> roleNames = new ArrayList<>();
                for (Long roleId : roleIds) {
                    SysRoleDTO roleDTO = sysRoleService.selectById(roleId);
                    if (roleDTO != null) {
                        roleNames.add(roleDTO.getRoleName());
                    }
                }

                userVO.setRoleIds(roleIds);
                userVO.setRoleNames(roleNames);
            }
        } catch (Exception e) {
            log.error("查询用户[{}]角色信息失败", userId, e);
        }
    }
}